
class Solution {
public:
    int dx[4] = { 0,1,0 ,- 1 };
    int dy[4] = { 1,0,-1,0 };

    vector<int> spiralArray(vector<vector<int>>& array) {
        if(array.size()==0||array[0].size()==0)return {};
        int n = array.size() * array[0].size();
        vector<int>ret;
        int pos = 0;
        int i = 0; int j = 0;
        vector<vector<bool>>vis(array.size(), vector<bool>(array[0].size(), 0));
        while (ret.size() < n)
        {
            ret.push_back(array[i][j]); vis[i][j] = true;
            int a = i + dx[pos];
            int b = j + dy[pos];
            if (a < 0 || a >= array.size() || b < 0 || b >= array[0].size() || vis[a][b] == true)
            {
                pos++;
                pos %= 4;
                a = i + dx[pos];
                b = j + dy[pos];

            }
            i =a;j=b;
        }
        return ret;
    }
};
